from django.shortcuts import render, HttpResponse
from django.views.generic import View

from dwebsocket.decorators import accept_websocket
from urllib import parse
import os,shutil, time

import threading
# Create your views here.
from app.operation.SpiderImages import SpiderImages
from utility.FileManage import FileManage

@accept_websocket
def GetLog(request):
    if request.is_websocket():
        print(1)
        a = request.websocket.wait().decode()
        print(a)
        request.websocket.send('下载完成'.encode('utf-8'))

class Index(View):
    def get(self, request):
        return render(request, 'index.html')


class Spider(View):
    def get(self, request):
        key = input("请输入搜索关键词: ")
        # key = request.GET.get('key','key')
        key = parse.quote(key)
        S = SpiderImages(key)
        S.get_all_images_url_list_and_save()
        S.read_and_download()
        print('下载完成')
        return HttpResponse('ok')


class OperatingPicture(View):

    def get(self,request):
        # 获取训练集下的所有目录
        dir_name = list()
        for dir, j, file_list in os.walk('../../data_set/training_set/'):
            dir_name.extend(j)

        print(dir_name)
        S = FileManage()
        file_path_list,file_name = S.get_file_path_list_from_dir(r'../../data_set/unsigned_set/')
        pics = file_name

        return render(request, 'image_operation.html',{
            'dir_name': dir_name,
            'pics': pics,
        })

    def post(self,request):
        data = request.POST.get('data')
        # 获取过来的是字符串处理成列表
        data = data.split(',')
        for item in data:
            if item:
                try:
                    os.remove(r'../../data_set/unsigned_set/{}'.format(item))
                except:
                    print('删除完成.')
        return HttpResponse('ok')

class Remove(View):

    def post(self,request):
        data = request.POST.get('data')
        classify = request.POST.get('classify')
        # 获取过来的是字符串处理成列表
        data = data.split(',')
        for item in data:
            # 切片之后存在空
            if item:
                try:
                    shutil.move(r'../../data_set/unsigned_set/{}'.format(item), r'../../data_set/training_set/{0}/{1}'.format(classify,item))
                except:
                    print('移动未成功，查看是否存在图片目录')
        return HttpResponse('Ok')
